import time
import datetime
import os

class Logcat:
    # ANSI 颜色转义码
    _COLOR_D = "\033[94m"    # 蓝色(DEBUG)
    _COLOR_E = "\033[91m"    # 红色(ERROR)
    _COLOR_W = "\033[93m"    # 黄色(WARNING)
    _COLOR_RESET = "\033[0m" # 重置颜色
    
    # 解析临时目录路径
    _LOG_FILE = os.path.expandvars("%temp%\\logcat_temp.log")

    @staticmethod
    def d(tag, message):
        timestamp_ms = int(time.time() * 1000)
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
        print(f"[{timestamp_ms}] | [{current_time}] | Info: {Logcat._COLOR_D}{tag}{Logcat._COLOR_RESET}: {message}")
        # 使用w模式写入（覆盖原有内容）
        Logcat._write_log(timestamp_ms, current_time, "Info", tag, message)
    
    @staticmethod
    def e(tag, message):
        timestamp_ms = int(time.time() * 1000)
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
        print(f"[{timestamp_ms}] | [{current_time}] | Error: {Logcat._COLOR_E}{tag}{Logcat._COLOR_RESET}: {message}")
        Logcat._write_log(timestamp_ms, current_time, "Error", tag, message)
    
    @staticmethod
    def w(tag, message):
        timestamp_ms = int(time.time() * 1000)
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
        print(f"[{timestamp_ms}] | [{current_time}] | Warning: {Logcat._COLOR_W}{tag}{Logcat._COLOR_RESET}: {message}")
        Logcat._write_log(timestamp_ms, current_time, "Warning", tag, message)
    
    @staticmethod
    def _write_log(timestamp, datetime_str, level, tag, message):
        """使用w模式写入，每次覆盖之前的日志"""
        try:
            with open(Logcat._LOG_FILE, "w", encoding="utf-8") as f:
                log_line = f"{timestamp} | {datetime_str} | {level} | {tag} : {message}\n"
                f.write(log_line)
        except Exception as e:
            print(f"日志写入失败: {str(e)} (文件路径: {Logcat._LOG_FILE})")

# 示例用法（多次调用会覆盖日志，只保留最后一条）
if __name__ == "__main__":
    Logcat.d("Test", "第一条日志")  # 会被覆盖
    Logcat.e("Test", "第二条日志")  # 会被覆盖
    Logcat.w("Test", "最后一条日志") # 最终保留这条
